<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <style>
        .shadow {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>

<body>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
    <div class="shadow"></div>
</body>
<script>
    class DragEle {
        posX = null;
        posY = null;
        constructor(ele) {
            this.target = ele;
            this.init();
        }
        init() {
            this.randColor();
            this.dragStart();
        }
        dragStart() {
            var _this = this;
            this.target.onmousedown = function (e) {
                var e = e || window.event;
                var posX = e.offsetX;
                var posY = e.offsetY;

                _this.posX = posX;
                _this.posY = posY;

                _this.dragMove();
                _this.dragEnd();
            }
        }
        dragMove() {
            document.onmousemove = () => {
                var e = e || window.event;
                var x = e.pageX - this.posX;
                var y = e.pageY - this.posY;
                console.log(x, y);

                this.target.style.left = x + "px";
                this.target.style.top = y + "px";
            }
        }
        dragEnd() {
            // 鼠标在文档中任意位置松开时  清除移动
            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
            }
        }
        randColor() {
            var str = "0123456789abcdef";
            var colorStr = "#";
            for (var i = 0; i < 6; i++) {
                var index = Math.floor(Math.random() * str.length);
                var char = str.charAt(index);
                colorStr += char;
            }
            this.target.style.backgroundColor = colorStr;

        }

    }


    var shadowList = document.querySelectorAll(".shadow");

    for (var i = 0; i < shadowList.length; i++) {
        var shadow = shadowList[i];
        var o = new DragEle(shadow);
        console.log(o);
    }




</script>

</html>